clear all
*cap log close
set more off
set seed 603


* relationship between stringency and predicted unbunched speed -----------------------------
#delimit ;
global cov = "female age agesq age_miss race_b race_h race_o race_u priorprison local
logzip zipincome_miss logprice veh_miss speed_py1 other_py1 crashany_py1" ;
#delimit cr

* cross-partition predictions ---------
use "${data}/out/4-main", clear
reghdfe speeddiff ${cov} if partRANDOM==1 & lenientpart==1, absorb(totfe)
predict speedhat_1 
reghdfe speeddiff ${cov} if partRANDOM==2 & lenientpart==1, absorb(totfe) 
predict speedhat_2 
gen speedhat = .
replace speedhat = speedhat_1 if partRANDOM==2
replace speedhat = speedhat_2 if partRANDOM==1 

reghdfe speedhat Z, absorb(totfe) cluster(officerid)
local bprint = "{it:{&beta}} = `:di %5.4f _b[Z]' (`:di %5.4f _se[Z]')"

reghdfe speedhat, absorb(totfe) resid 
predict rspeedhat, resid 
reghdfe Z, absorb(totfe) resid 
predict rz, resid 
binscatter rspeedhat rz, gen(bin) nodraw nq(20)  
collapse (mean) rspeedhat rz, by(bin) fast 

#delimit ;
scatter rspeedhat rz, mcolor(dknavy) msymbol(Oh)  ||
lfit    rspeedhat rz, lcolor(dknavy) lpattern(dash) 
graphregion(color(white)) plotregion(lcolor(black) lwidth(medthin))
ylab(-0.1(0.05)0.1,nogrid) xlab(-0.5(0.25)0.5,nogrid) legend(off)
xtitle("Officer Stringency") ytitle("Predicted True Speed")
text(-0.05 -0.3 "`bprint'", place(s)) ;
#delimit cr
graph export "${out}/apx_iv/speeds_predicted.pdf", replace 
* -------------------------------------------------------------------------------------------



* relationship between stringency and tix at no bunching speeds -----------------------------
use "${data}/out/4-main", clear
keep officerid 
duplicates drop 
merge 1:m officerid using  "${data}/out/2-stopsfhp", keep(3) nogen 
keep if viol_code==575 & !mi(speeddiff)
egen totfe = group(countynum highway year month wknd shift)

gen slow = (speeddiff<9)
reghdfe slow, absorb(officerid totfe, savefe)
qui summ __hdfe2  
gen rslow = __hdfe1+`r(mean)'
collapse (mean) rslow, by(officerid)
tempfile temp
save   	`temp'

use "${data}/out/4-main"
reghdfe Z, absorb(totfe) resid 
predict rz, resid 
collapse (mean) rz, by(officerid)
merge 1:1 officerid using `temp'
reg rslow rz, r 
local bprint = "{it:{&beta}} = `:di %5.4f _b[rz]' (`:di %5.4f _se[rz]')"

binscatter rslow rz, gen(bin) nodraw nq(15)  
collapse (mean) rslow rz, by(bin) fast 

#delimit ;
scatter rslow rz, mcolor(dknavy) msymbol(Oh)  ||
lfit    rslow rz, lcolor(dknavy) lpattern(dash) 
graphregion(color(white)) plotregion(lcolor(black) lwidth(medthin))
ylab(-0.1(0.05)0.1,nogrid) xlab(-0.5(0.25)0.5,nogrid) legend(off)
xtitle("Officer Stringency") ytitle("Adjusted Share of Citations for 6-8 MPH")
text(-0.025 -0.3 "`bprint'", place(s)) ;
#delimit cr
graph export "${out}/apx_iv/speeds_slow.pdf", replace 
* ------------------------------------------------------------------------------------------



